72. Edit Distance - LeetCode Solution


String Dynamic Programming

Python Code:

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        if not word1 and not word2:
            return 0
        if word1 == word2:
            return 0
        dp = []
       
        for i in range(len(word1)+1):
            a = []
            for j in range(len(word2)+1):
                a.append(0)
            dp.append(a)
            
        for i in range(len(word1)+1):
            dp[i][0] = i
        
        for i in range(len(word2) +1):
            dp[0][i] = i
            
        
        for i in range(1, len(word1)+1, 1):
            for j in range(1, len(word2)+1, 1):
                if word1[i-1] == word2[j-1]:
                    dp[i][j] = dp[i-1][j-1]
                else:
                    dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
        return dp[-1][-1]


Comments

Submit
0 Comments
More Questions

766A - Mahmoud and Longest Uncommon Subsequence
701B - Cells Not Under Attack
702A - Maximum Increase
1656D - K-good
1426A - Floor Number
876A - Trip For Meal
1326B - Maximums
1635C - Differential Sorting
961A - Tetris
1635B - Avoid Local Maximums
20A - BerOS file system
1637A - Sorting Parts
509A - Maximum in Table
1647C - Madoka and Childish Pranks
689B - Mike and Shortcuts
379B - New Year Present
1498A - GCD Sum
1277C - As Simple as One and Two
1301A - Three Strings
460A - Vasya and Socks
1624C - Division by Two and Permutation
1288A - Deadline
1617A - Forbidden Subsequence
914A - Perfect Squares
873D - Merge Sort
1251A - Broken Keyboard
463B - Caisa and Pylons
584A - Olesya and Rodion
799A - Carrot Cakes
1569B - Chess Tournament